package com.web.exiaodao.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;
import com.web.exiaodao.business.entity.CheckInTable;
import com.web.exiaodao.business.repository.CheckInTableRepository;
import com.web.exiaodao.business.service.CheckInTableService;
import com.web.exiaodao.remote.vo.CheckInTableVo;
import com.web.exiaodao.remote.vo.UserVo;

@Service("CheckInTableService")
@Transactional(readOnly = false)
public class CheckInTableServiceImpl extends BaseService<CheckInTable> implements CheckInTableService {

	private static final Logger LOGGER = Logger.getLogger(CheckInTableServiceImpl.class);

	@Autowired
	private CheckInTableRepository checkInTableRepository;
	
	/**
	 * 查询单条CheckInTable信息
	 * //@param tId
	 * @return 返回单个CheckInTable对象
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<CheckInTable> findOne(Long modelId) throws BusinessException {
		CheckInTable obj = new CheckInTable();
		if(modelId != 0){
			obj = checkInTableRepository.findByIdAndStatusNot(modelId,XaConstant.Status.delete);
		}
		XaResult<CheckInTable> xr = new XaResult<CheckInTable>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(obj);
			LOGGER.info("后台----->查询单个实体----->CheckInTable");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	/**
	 * 分页查询状态非status的CheckInTable数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象CheckInTable集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<CheckInTable>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<CheckInTable> page = checkInTableRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), CheckInTable.class), pageable);
		XaResult<Page<CheckInTable>> xr = new XaResult<Page<CheckInTable>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态不等于）----->CheckInTable");
		return xr;
	}

	/**
	 * 分页查询状态status的CheckInTable数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象CheckInTable集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<CheckInTable>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<CheckInTable> page = checkInTableRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), CheckInTable.class), pageable);
		XaResult<Page<CheckInTable>> xr = new XaResult<Page<CheckInTable>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态等于）----->CheckInTable");
		return xr;
	}

	/**
	 * 保存CheckInTable信息
	 * @param model
	 * @return
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<CheckInTable> saveOrUpdate(CheckInTable model) throws BusinessException {
		CheckInTable obj = null;
		if(XaUtil.isNotEmpty(model.getId())){
			obj = checkInTableRepository.findOne(model.getId());
		}else{
			obj = new CheckInTable();
		}
	    obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
	    obj.setCheckIn_DateTime(XaUtil.isNotEmpty(model.getCheckIn_DateTime()) ? model.getCheckIn_DateTime() : obj.getCheckIn_DateTime());
	    obj.setCheck_Count(XaUtil.isNotEmpty(model.getCheck_Count()) ? model.getCheck_Count() : obj.getCheck_Count());
		obj = checkInTableRepository.save(obj);
		XaResult<CheckInTable> xr = new XaResult<CheckInTable>();
		xr.setObject(obj);
		LOGGER.info("后台新增或编辑数据成功！");
		return xr;
	}

	/**
	 * 修改CheckInTable状态，可一次修改多条   3删除  -1锁定  1正常
	 * @param userId
	 * @param modelIds
	 * @param status
	 * @return 返回CheckInTable对象
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<CheckInTable> multiOperate(
			String modelIds,Integer status) throws BusinessException {
		XaResult<CheckInTable> xr = new XaResult<CheckInTable>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				CheckInTable obj = checkInTableRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = checkInTableRepository.save(obj);
				}
			}
		}
		LOGGER.info("批量修改数据状态成功！");
		return xr;
	}

	/**
	 * 分页查询CheckInTable
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public XaResult<Page<CheckInTableVo>> findCheckInTableList(Integer nextPage,
			Integer pageSize, Map<String, Object> filterParams)
			throws BusinessException {
		StringBuffer sql=new StringBuffer("SELECT c.`id`,u.`user_name`,c.`check_in_date_time`,c.`check_count`,c.`status` ");
		sql.append("FROM `tb_xa_checkintable` c ");
		sql.append("LEFT JOIN `tb_xa_user` u ON u.`id` = c.`user_id` ");
		sql.append(" WHERE c.`status`<>").append(XaConstant.Status.delete);
		//统计数据库中数据个数
		StringBuffer sql1=new StringBuffer("SELECT COUNT(*) ");
		sql1.append("FROM `tb_xa_checkintable` c ");
		sql1.append("LEFT JOIN `tb_xa_user` u ON u.`id` = c.`user_id` ");
		sql1.append(" AND c.`status`<>").append(XaConstant.Status.delete);
		//查询条件
		if(XaUtil.isNotEmpty(filterParams.get("Like_userName"))){
			sql.append(" AND u.`user_name` ").append(" like '%").append(filterParams.get("Like_userName")).append("%' ");
			sql1.append(" AND u.`user_name` ").append(" like '%").append(filterParams.get("Like_userName")).append("%' ");
		}
		sql.append(" ORDER BY c.`create_time` desc");
		sql1.append(" ORDER BY c.`create_time` desc");
		List<Object[]> objs=this.query(sql.toString(), nextPage*pageSize, pageSize);
		List<CheckInTableVo> vos=new ArrayList<CheckInTableVo>();
		for (Object[] obj : objs) {	
			UserVo uVo = new UserVo();
			CheckInTableVo vo = new CheckInTableVo();
			vo.setId(Long.valueOf(obj[0].toString()));
			uVo.setUserName(XaUtil.isEmpty(obj[1])?"":obj[1].toString());
			vo.setCheckIn_DateTime(XaUtil.isEmpty(obj[2])?"":obj[2].toString());
			vo.setCheck_Count(XaUtil.isEmpty(obj[1])?0:Long.valueOf(obj[3].toString()));
			vo.setUserVo(uVo);
			vos.add(vo);
		}
		//执行查询语句
		List<Object[]> obj1=this.query(sql1.toString(), null, null);
		//将得到的查询结果强转成int类型
		int count=Integer.parseInt(obj1.get(0)+"");				
		//调用分页
		Page<CheckInTableVo> page= new MyPage<CheckInTableVo>(nextPage.intValue(),pageSize.intValue(),vos,count);
		//创建结果集对象xr
		XaResult<Page<CheckInTableVo>> xr=new XaResult<Page<CheckInTableVo>>();
		//将page放入xr
		xr.setObject(page);
		return xr;
	}
	
}
